package impl;

import java.io.UnsupportedEncodingException;
import java.util.Date;

import api.ejb.IPostman;
import javax.ejb.Stateless;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.jboss.logging.Logger;

/**
 * Session Bean implementation class Postman
 */
@Stateless(name = "IPostman")
public class Postman implements IPostman {

	private static final Logger log = Logger.getLogger(Postman.class);

	
	/**
	 * Default constructor.
	 */
	public Postman() {

	}

	@Override
	public boolean sendMail(String to, String subject, String message) {
		log.info("Executing ---------->");

		new MailThread("sendMail_" + (new Date()), to, subject, message)
				.start();
		log.info("<--------------- Done");

		return true;
	}

	class MailThread extends Thread {
		String to;
		String subject;
		String message;

		public MailThread(String tName, String to, String subject,
				String message) {
			super(tName);
			this.to = to;
			this.subject = subject;
			this.message = message;
		}

		public void run() {

			try {
				Context initCtx;

				initCtx = new InitialContext();
				Session session = (Session) initCtx.lookup("java:/GMail");
				Message m = new MimeMessage(session);
				InternetAddress xxx = new InternetAddress(
						"PhaseBookSupportTeam");
				try {
					xxx.setPersonal("PhaseBookSupportTeam");
					m.setFrom(xxx);
				} catch (UnsupportedEncodingException e) {
					m.setFrom();
				}
				InternetAddress toList[] = new InternetAddress[1];
				toList[0] = new InternetAddress(to);
				m.setRecipients(Message.RecipientType.TO, toList);

				m.setSubject("[PhaseBook] " + subject);
				m.setContent(message + "\n\n The PhaseBook Team (Southsiders)",
						"text/plain");
				Transport.send(m);
			} catch (NamingException e) {
				e.printStackTrace();

			} catch (AddressException e) {
				e.printStackTrace();
			} catch (MessagingException e) {
				e.printStackTrace();
			}

			System.out.println(getName() + " finished! ");
		}
	}

}
